<template>
	<view>
		<view class="goods-list">
			<view v-for="(goods, index) in goodsList" :key="index" @click="goDetail(goods)">
				<my-goods :goods="goods"></my-goods>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			// 请求参数对象
			queryObj: {
				query: '', // 查询关键词
				cid: '', // 商品分类id
				pagenum: 1, // 页码
				pagesize: 10 // 每页显示多少条数据
			},
			goodsList: [],
			total: 0, // 总数据
			
			isloading: false // 是否在请求数据
		};
	},
	filters: {
		tofixed(num) {
			return Number(num).toFixed(2);
		}
	},
	onLoad(options) {
		// 将页面参数转存到 this.queryObj 对象中
		this.queryObj.query = options.query || '';
		this.queryObj.cid = options.cid || '';

		this.getGoodsList();
	},
	methods: {
		// 获取商品列表数据的方法
		async getGoodsList(callback) {
			// 打开节流阀
			this.isloading = true;
			// 发起请求
			const { data: res } = await uni.$http.get(
				'/api/public/v1/goods/search',
				this.queryObj
			);
			// 关闭节流阀
			this.isloading = false;
			callback && callback();
			if (res.meta.status !== 200) return uni.$showMsg();
			// 为数据赋值
			this.goodsList = [...this.goodsList, ...res.message.goods];
			this.total = res.message.total;
			// console.log(this.goodsList);
		},
		// 跳转商品详情
		goDetail(goods) {
		  uni.navigateTo({
		    url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id
		  })
		}
	},
	// 上拉触底
	onReachBottom() {
		// 判断还有没有数据
		if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total)
			return uni.$showMsg('数据加载完毕');
		// 如果正在发起请求，则返回
		if (this.isloading) return;
		this.queryObj.pagenum++;
		this.getGoodsList();
	},
	onPullDownRefresh() {
		// 重置数据
		this.queryObj.pagenum = 1;
		this.total = 0;
		this.isloading = false;
		this.goodsList = [];
		// 重新发起请求
		this.getGoodsList(() => uni.stopPullDownRefresh());
	}
};
</script>

<style lang="scss">
.goods-item {
	display: flex;
	padding: 10px 5px;
	border-bottom: 1px solid #f0f0f0;

	.goods-item-left {
		margin-right: 5px;

		.goods-pic {
			width: 100px;
			height: 100px;
			display: block;
		}
	}

	.goods-item-right {
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.goods-name {
			font-size: 13px;
		}

		.goods-price {
			font-size: 16px;
			color: #c00000;
		}
	}
}
</style>
